package core

import (
	"com.go-micro.code/todolist/go-micro-todolist/task/model"
	"com.go-micro.code/todolist/go-micro-todolist/task/services"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/Shopify/sarama"
	"github.com/spf13/viper"
)

type TaskService struct {
}

func CreateTaskModel(item model.Task) *services.TaskModel {
	return &services.TaskModel{
		Id:         uint64(item.ID),
		Uid:        uint64(item.Uid),
		Title:      item.Title,
		Content:    item.Content,
		StartTime:  item.StartTime,
		EndTime:    item.EndTime,
		Status:     int64(item.Status),
		CreateTime: item.CreatedAt.Unix(),
		UpdateTime: item.UpdatedAt.Unix(),
	}
}

func (*TaskService) CreateTask(ctx context.Context, req *services.TaskRequest, resp *services.TaskDetailResponse) error {
	msg := &sarama.ProducerMessage{
		Topic: viper.GetString("kafka.topic"),
	}
	body, err := json.Marshal(req) //序列化
	if err != nil {
		return err
	}
	msg.Value = sarama.ByteEncoder(body)
	_, offset, err := model.MQ.SendMessage(msg)
	fmt.Println("offset:", offset)
	return err

}

// 实现备忘录服务接口 获取备忘录列表
func (*TaskService) GetTasksList(ctx context.Context, req *services.TaskRequest, resp *services.TaskListResponse) error {
	if req.Limit == 0 {
		req.Limit = 10
	}
	var taskData []model.Task
	var count uint32
	err := model.DB.Offset(req.Start).Limit(req.Limit).Where("uid=?", req.Uid).Find(&taskData).Error
	if err != nil {
		return errors.New("mysql find : " + err.Error())
	}
	// 统计数量
	model.DB.Model(&model.Task{}).Where("uid=?", req.Uid).Count(&count)
	// 返回proto里面定义的类型
	var taskRes []*services.TaskModel
	for _, item := range taskData {
		taskRes = append(taskRes, CreateTaskModel(item))
	}
	resp.TaskList = taskRes
	resp.Count = count
	return nil
}

func (*TaskService) GetTask(ctx context.Context, req *services.TaskRequest, resp *services.TaskDetailResponse) error {
	taskData := model.Task{}
	model.DB.First(&taskData, req.Id)
	taskRes := CreateTaskModel(taskData)
	resp.TaskDetail = taskRes
	return nil
}

// 修改备忘录
func (*TaskService) UpdateTask(ctx context.Context, req *services.TaskRequest, resp *services.TaskDetailResponse) error {
	taskData := model.Task{}
	// 查找该用户的这条信息
	model.DB.Model(&model.Task{}).Where("id= ? AND uid=?", req.Id, req.Uid).First(&taskData)
	taskData.Title = req.Title
	taskData.Status = int(req.Status)
	taskData.Content = req.Content
	model.DB.Save(&taskData)
	resp.TaskDetail = CreateTaskModel(taskData)
	return nil
}

// 删除备忘录
func (*TaskService) DeleteTask(ctx context.Context, req *services.TaskRequest, resp *services.TaskDetailResponse) error {
	err := model.DB.Model(&model.Task{}).Where("id =? AND uid=?", req.Id, req.Uid).Delete(&model.Task{}).Error
	if err != nil {
		return errors.New("删除失败：" + err.Error())
	}
	return nil
}
